"""
客户管理服务类
负责客户的CRUD操作和Stripe客户同步
"""

import stripe
import uuid
import logging
from datetime import datetime
from typing import Optional, Dict, Any, List
from fastapi import HTTPException

from utils.config import Config
from utils.data_store import DataStore
from models.customer_models import CustomerCreateRequest, CustomerUpdateRequest

logger = logging.getLogger(__name__)


class CustomerService:
    """客户管理服务类"""
    
    def __init__(self):
        self.customers = DataStore.load_data(Config.CUSTOMERS_FILE)
    
    def create_customer(self, request: CustomerCreateRequest) -> Dict[str, Any]:
        """创建新客户"""
        # 检查邮箱是否已存在
        for customer_id, customer_data in self.customers.items():
            if customer_data.get('email') == request.email:
                raise HTTPException(
                    status_code=400, 
                    detail=f"邮箱 {request.email} 已被注册"
                )
        
        try:
            # 在Stripe中创建客户
            stripe_customer = stripe.Customer.create(
                email=request.email,
                name=request.name,
                phone=request.phone,
                address=request.address,
                metadata=request.metadata or {}
            )
            
            # 生成本地客户ID
            local_customer_id = str(uuid.uuid4())
            
            # 构建客户数据
            customer_data = {
                'id': local_customer_id,
                'stripe_customer_id': stripe_customer.id,
                'email': request.email,
                'name': request.name,
                'phone': request.phone,
                'address': request.address,
                'metadata': request.metadata or {},
                'created_at': datetime.now().isoformat(),
                'updated_at': datetime.now().isoformat(),
                'is_active': True
            }
            
            # 保存到本地存储
            self.customers[local_customer_id] = customer_data
            DataStore.save_data(Config.CUSTOMERS_FILE, self.customers)
            
            logger.info(f"客户创建成功: {local_customer_id} - {request.email}")
            return customer_data
            
        except stripe.error.StripeError as e:
            logger.error(f"Stripe错误: {str(e)}")
            raise HTTPException(status_code=400, detail=f"Stripe错误: {str(e)}")
        except Exception as e:
            logger.error(f"创建客户失败: {str(e)}")
            raise HTTPException(status_code=500, detail="创建客户失败")
    
    def get_customer(self, customer_id: str) -> Optional[Dict[str, Any]]:
        """获取客户信息"""
        return self.customers.get(customer_id)
    
    def get_customer_by_email(self, email: str) -> Optional[Dict[str, Any]]:
        """根据邮箱获取客户"""
        for customer_data in self.customers.values():
            if customer_data.get('email') == email:
                return customer_data
        return None
    
    def list_customers(self, limit: int = 100, offset: int = 0) -> List[Dict[str, Any]]:
        """列出客户"""
        customers_list = list(self.customers.values())
        return customers_list[offset:offset + limit]
    
    def update_customer(self, customer_id: str, request: CustomerUpdateRequest) -> Optional[Dict[str, Any]]:
        """更新客户信息"""
        if customer_id not in self.customers:
            return None
        
        customer_data = self.customers[customer_id]
        
        # 检查邮箱是否被其他客户使用
        if request.email and request.email != customer_data.get('email'):
            for cid, cdata in self.customers.items():
                if cid != customer_id and cdata.get('email') == request.email:
                    raise HTTPException(
                        status_code=400, 
                        detail=f"邮箱 {request.email} 已被其他客户使用"
                    )
        
        try:
            # 更新Stripe客户
            update_data = {}
            if request.email:
                update_data['email'] = request.email
            if request.name:
                update_data['name'] = request.name
            if request.phone is not None:
                update_data['phone'] = request.phone
            if request.address is not None:
                update_data['address'] = request.address
            if request.metadata is not None:
                update_data['metadata'] = request.metadata
            
            if update_data:
                stripe.Customer.modify(
                    customer_data['stripe_customer_id'],
                    **update_data
                )
            
            # 更新本地数据
            for key, value in update_data.items():
                customer_data[key] = value
            
            customer_data['updated_at'] = datetime.now().isoformat()
            self.customers[customer_id] = customer_data
            DataStore.save_data(Config.CUSTOMERS_FILE, self.customers)
            
            logger.info(f"客户更新成功: {customer_id}")
            return customer_data
            
        except stripe.error.StripeError as e:
            logger.error(f"Stripe错误: {str(e)}")
            raise HTTPException(status_code=400, detail=f"Stripe错误: {str(e)}")
        except Exception as e:
            logger.error(f"更新客户失败: {str(e)}")
            raise HTTPException(status_code=500, detail="更新客户失败")
    
    def delete_customer(self, customer_id: str) -> bool:
        """删除客户"""
        if customer_id not in self.customers:
            return False
        
        customer_data = self.customers[customer_id]
        
        try:
            # 删除Stripe客户
            stripe.Customer.delete(customer_data['stripe_customer_id'])
            
            # 从本地存储中删除
            del self.customers[customer_id]
            DataStore.save_data(Config.CUSTOMERS_FILE, self.customers)
            
            logger.info(f"客户删除成功: {customer_id}")
            return True
            
        except stripe.error.StripeError as e:
            logger.error(f"Stripe错误: {str(e)}")
            raise HTTPException(status_code=400, detail=f"Stripe错误: {str(e)}")
        except Exception as e:
            logger.error(f"删除客户失败: {str(e)}")
            raise HTTPException(status_code=500, detail="删除客户失败")
    
    def reload_data(self):
        """重新加载数据"""
        self.customers = DataStore.load_data(Config.CUSTOMERS_FILE)
